package jp.sourceforge.akjrcp.psp.imageconvert;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import jp.sourceforge.akjrcp.util.image.ImageUtils;
/**
 * 
 *@deprecated use com.akjava.lib.standards
 */
public class ImageTurner extends AbstractImageChanger{
	public static Log log=LogFactory.getLog(ImageTurner.class);
	public static final int TURN_RIGHT=0;
	public static final int TURN_LEFT=1;
	private int turnMode;
	
	public ImageTurner(){
		time=System.currentTimeMillis();
	}
	
	public void changeImage(String imageFileName,InputStream imageInput,File exportDir) throws IOException{
		if(cancel){
			return;
		}
		BufferedImage baseImage=imageLoader.loadImage(imageFileName,imageInput);
		BufferedImage argb=toARGB(baseImage);
		baseImage.getGraphics().dispose();//for keep memory
		BufferedImage fit=ImageUtils.fitImage(argb,height,width);
		argb.getGraphics().dispose();
		BufferedImage turnnedImage=turnImage(fit);
		fit.getGraphics().dispose();
		
		
		BufferedImage rgb=toRGB(turnnedImage);
		turnnedImage.getGraphics().dispose();
		
		saveImage(rgb,imageFileName,exportDir);
		rgb.getGraphics().dispose();
		
		System.gc();
	}
	
	public BufferedImage turnImage(BufferedImage img){
		log.info(img.getWidth()+","+img.getHeight());
		BufferedImage ret=new BufferedImage(img.getHeight(),img.getWidth(),BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2=(Graphics2D) ret.getGraphics();
		AffineTransform af = new AffineTransform();
		
		if(turnMode==TURN_RIGHT){
		af.setToTranslation(img.getHeight(), 0d);
		af.rotate(90 * Math.PI/180);//turn right
		}else{
		af.setToTranslation(0, img.getWidth());
		af.rotate(270 * Math.PI/180);//turn right	
		}
		g2.setTransform(af);
		g2.drawImage(img,0,0,null);
		return ret;
	}
	
	public int getTurnMode() {
		return turnMode;
	}

	public void setTurnMode(int turnMode) {
		this.turnMode = turnMode;
	}
}
